import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userApi } from '../request'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const token = ref(null)
  const isAuthenticated = computed(() => !!token.value)

  // 从 localStorage 恢复登录状态
  const initializeAuth = () => {
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')
    if (savedToken && savedUser) {
      token.value = savedToken
      user.value = JSON.parse(savedUser)
    }
  }

  // 登录
  const login = async (email: string, password: string) => {
    try {
      const response = await userApi.login({ email, password })
      
      token.value = response.access_token
      user.value = response.user
      
      localStorage.setItem('token', token.value)
      localStorage.setItem('user', JSON.stringify(user.value))
      
      return true
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 注册
  const register = async (userData: {
    email: string
    password: string
    name: string
    familyId: string
  }) => {
    try {
      const response = await userApi.register(userData)
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  // 更新用户信息
  const updateUser = async (familyId: string) => {
    if (!user.value?.id) return false

    try {
      const response = await userApi.updateUser(user.value.id, { familyId })
      
      user.value = {
        ...user.value,
        familyId
      }
      localStorage.setItem('user', JSON.stringify(user.value))
      
      return true
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return false
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  return {
    user,
    token,
    isAuthenticated,
    initializeAuth,
    login,
    register,
    updateUser,
    logout
  }
})